在ㄧ開始學習 vuex 觀念的時候,還有點搞不清楚怎麼區分資料,於是找了一個
小練習實作。
我們有一個簡單的員工資料庫,用幾隻 API 來實作員工資料的 CRUD
這是練習的資料夾結構
員工的 vuex 設計
import Vue from "vue";
import Vuex from "vuex";
import server from "@/utils/API.js";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
employees: [],
newEmployee: {
name: null,
email: null
}
},
getters: {
employees(state) {
return state.employees;
}
},
mutations: {
updateNewEmployeeName(state, name) {
state.newEmployee.name = name;
},
updateNewEmployeeEmail(state, email) {
state.newEmployee.email = email;
},
pushToEmployees(state, responseEmployee) {
state.employees.push(responseEmployee);
},
setEmployees(state, data) {
state.employees = data;
},
updateEmployee(state, cachedEmployee) {
console.log("updatedId", cachedEmployee.id);
this.state.employees = this.state.employees.map(employee => {
return employee.id === cachedEmployee.id ? cachedEmployee : employee;
});
},
deleteEmployee(state, id) {
state.employees = state.employees.filter(employee => employee.id !== id);
}
},
actions: {
async getEmployees({ commit }) {
const res = await server.get("/users");
commit("setEmployees", res);
},
async addNewEmployee(context) {
const responseEmployee = await server.post(
"/users",
context.state.newEmployee
);
context.commit("pushToEmployees", responseEmployee);
},
async editEmployee({ commit }, cachedEmployee) {
await commit("updateEmployee", cachedEmployee);
},
async deleteEmployee({ commit }, id) {
await server.delete(`/users/${id}`);
await commit("deleteEmployee", id);
}
}
});